# -*- coding: utf-8 -*-
# @Author  : caiweichao
# @explain : 接口返回值校验
import os

import allure

from Commons.operation_file.operation_ymal import ReadYaml
from Commons.util.json_util import JsonUtil
from Commons.util.logs import Log

import jsonschema

from ConfigFile.contants_file import SCHEMA_DATA_PAHT


class ApiAssert:
    @staticmethod
    def assert_all_expected(jsonPath: str, check: str, response: str):
        """
        全部字段校验,将全部对返回值进行校验
        :param jsonPath:jsonpath
        :param check: 期望值
        :param response:
        :return:
        """
        if len(jsonPath := jsonPath.split("\n")) != len(check := check.split("\n")):
            return Exception("用例参数异常请检查！")
        try:
            for k, v in dict(zip(jsonPath, check)).items():
                if (k := JsonUtil.jsonToOneValue(response, rule=k)) == v:
                    Log.info(f"\n接口关键字段校验:{v} = {k}")
                else:
                    Log.error(f"接口关键字段校验未通过:{v} != {k}")
                    return False
            return True
        except Exception:
            Exception("校验异常请检查")

    @staticmethod
    def assert_jsonschema(response, schema_yaml):
        """
        jsonschema与实际结果断言方法
        :param response: 实际响应结果
        :param schema_yaml: schema_yaml的地址
        :return:
        """
        yamlAdress = os.path.join(SCHEMA_DATA_PAHT, f'{schema_yaml}.yaml')
        schema_yaml = ReadYaml(file_url=yamlAdress).get_every_config()
        try:
            Log.info("jsonschema校验开始")
            jsonschema.validate(instance=response, schema=schema_yaml)
            Log.info("jsonschema校验通过")
            allure.step(f"jsonschema校验通过")
        except jsonschema.exceptions.ValidationError or jsonschema.exceptions.SchemaError as e:
            Log.error(f"jsonschema校验失败，报错信息为： {e}")
            allure.step(f"jsonschema校验失败,报错信息为： {e}")
            raise e


if __name__ == '__main__':
    pass
